///////////////////////////////////////////////////////////////////////////////
/// Copyright (c) 2013, 10wmj.com
/// All rights reserved.
///
/// @file		MatchConnection.cpp
/// @brief		
///
/// @version	1.0
/// @author		liangX
/// @date		2013.10.08
///
///////////////////////////////////////////////////////////////////////////////

#include "DataBaseThread.h"
#include "ClientHandler.h"
#include "StreamBuffer.h"
#include "TLog.h"
#include "CsvDataMgr.h"
#include "Config.h"
#include "ClientHandler.h"
#include "GameLotteryNew.h"


using namespace std;

#define PUSH_RESP(SQL) PipeEventHandler::instance()->push_queue(SQL);

#define __THREAD_MYSQL_CONNECT__  1


void DataBaseThread::update(int index)
{
	SQLReq * req = SQLMemoryPool::instance()->mallocReq();
	snprintf(req->sql,sizeof(req->sql),"select 1");
	req->id =index;
	req->client		= NULL ;
	req->req_type	= REQ_TYPE_EXECUTE_COMMOND;

	onprint();
	DataBaseReadThreadPool::instance()->pushQueue( req );

}
void DataBaseThread::run( void * object )
{
	DbConfig &m_db_acct			= Config::instance()->m_account_db;
	if ( !connect( m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name , m_db_acct.db_username,m_db_acct.db_userpwd) )
	{
		printf("connect acct db faild ip =%s port=%d db=%s name=%s pwd=%s cn=%d\n",
			m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name ,
			m_db_acct.db_username,m_db_acct.db_userpwd ,Config::instance()->m_db_connect_count);
		return ;
	}

	while ( 1 )
	{
		m_sem.wait_sem();
		SQLRequestList temp ;
		m_mutex.lock();
		if ( m_requests.size() > 0 )
		{
			//temp = m_requests ;
			SQLRequestList::iterator iter = m_requests.begin();
			for ( ; iter != m_requests.end() ; iter++)
			{
				temp.push_back( *iter );
			}
			m_requests.clear();
		}
		m_mutex.unlock();
		SQLRequestList::iterator iter = temp.begin();
		for ( ; iter != temp.end() ;)
		{
			struct  timeval    tv_start, tv_end;  gettimeofday(&tv_start,NULL);
			SQLReq * req = (*iter);
			try
			{
				switch ( req->req_type )
				{
				case REQ_TYPE_LOGIN:
				case REQ_TYPE_CHECKSESSION:
					handleLogin( req );
					break;
				case REQ_TYPE_REGISTER:
					handleRegister( req );
					break;
				case REQ_TYPE_TASK_REWARD:
					handleReceiveTaskBonus( req );
					break;
				case REQ_TYPE_HONGBAO_TASK_REWARD:
					handleReceiveHongbaoTaskBonus( req );
					break;
				case REQ_TYPE_ONLINE_REWARD:
					handleOnlineReward( req );
					break;
				case REQ_TYPE_RECOMMEND_AWARD:
					handleRecommendAward( req );
					break;
				case REQ_TYPE_EXCHAGE_PRODUCT:
					handleExchangeProduct( req );
					break;
				case REQ_TYPE_CHARGE_INFO:
					handleChargeInfo( req );
					break;
				case REQ_TYPE_CLIENT_COMMIT_CHARGE_RESULT:
					handleChargeResult( req );
					break;
				case REQ_TYPE_HTTP_COMMIT_CHARGE_RESULT:
					handleHttpChargeResult( req );
					break;
				case REQ_TYPE_CREATE_ORDER:
					handleCreateOrderResult( req );
					break;
				case REQ_TYPE_UPDATE_USER_INFO:
					handleUpdateUserInfo( req );
					break;
				case REQ_TYPE_UPDATE_USER_INFO_EX:
					handleDbUpdateUserInfoEx( req );
					break;
				case REQ_TYPE_FINISH_PAY_RESULT:
					handleFinishPayResult(req );
					break;
				case REQ_TYPE_FINISH_PAY_OFF_LINE:
					handleFinishPayOffLine(req );
					break;
				case REQ_TYPE_SIGNIN:
					{
						handleRecvSingInAward( req  );
						break;
					}
				case REQ_TYPE_UPDATE_WEALTH:
					{
						ExecCommand( req );
						break;
					}
				case REQ_TYPE_BIND_ACCOUNT:
					{
						handleBindAccount( req );
						break;
					}
				case REQ_TYPE_BIND_PHONE:
					{
						handleBindPhone( req );
						break;
					}
				case REQ_TYPE_DEPOSIT_BOX://保险箱
					{
						handleDeposit( req ); 
						break;
					}
				case REQ_TYPE_DEPOSIT_BOX_PWD:
					{
						ExecCommand( req ); 
						break;
					}
				case REQ_TYPE_UPDATE_NICKNAME:
					{
						handleUpdateNickName( req );
						break;
					}
				case REQ_TYPE_UPDATE_GOLD:
					{
						handleUpdateGold( req );
						break;
					}
				case REQ_TYPE_USE_EXPRESS:
					{
						ExecCommand( req );
						break;
					}
				case REQ_TYPE_TIGER:
					{
						handleBuyTiger(req);
						break;
					}
				case REQ_TYPE_EXECUTE_COMMOND:
				case REQ_TYPE_HTTP_RESET_PWD:
				case REQ_TYPE_UPDATE_HEADER_PIC:
				case REQ_TYPE_DELETE_TABLE:
					{
						ExecCommand( req );
						break;
					}
				case REQ_TYPE_LOTTERY_HANDLE:
					{
						handleLotteryMsg( req );
						break;
					}
				case REQ_TYPE_LOTTERY_REULT:
					{
						handleLotteryResult( req );
						break;
					}
				case REQ_TYPE_SEND_HORN:
					handleSendHorn( req );
					break;
				case REQ_TYPE_STRANSFER_GOLD:
					handleTransferGold( req );
					break;
				case REQ_TYPE_STRANSFER_GOLD_RECORD:
					handleTransferGoldRecord( req );
					break;
				case REQ_TYPE_GET_CHAT_MESSAGE:
					handleGetChatMessage( req );
					break;
				case REQ_TYPE_LOTTERYDRAW:
					handleLotteryDraw( req );
					break;
				case REQ_TYPE_GET_USER_WEALTH:
				case REQ_TYPE_GET_USER_WEALTH_EX:
					handleGetUserWealth( req );
					break;
				case REQ_TYPE_USER_SELL_BUY_GOODS:
					handleBuyOrSellGoods( req );
					break;
				case REQ_TYPE_SELL_GIFT:
					handleSellGift( req );
					break;
				case REQ_TYPE_FRIEND_GIVE_GFIT:
					handleGiveGift( req );
					break;
				case REQ_TYPE_CLEAR_LASTDAY_VAR:
					handleClearLastDayVar( req );
					break;
				case REQ_TYPE_FRIEND_ADD_BY_GFIT:
					{
						TQuery query ;
						if ( m_db.ExecuteQuery( req->sql , query ) )
						{
							handleFriendAddByGift( req , query  );
						}
						
					}
					break;
				case REQ_TYPE_BRC_SETTLE:
					handleBRCSettle( req );
					break;
				case REQ_TYPE_ENTER_ROOM:
					handleEnterRoomCheck(req);
					break;
				case REQ_TYPE_BRC_GET_LOTTERY:
					handleBRCGetLottery(req);
					break;
				case REQ_TYPE_UPDATE_GIFT_CNT:
					handleUpdateGiftNum(req);
					break;
				case ERQ_SHISHI_CAI_YAZHU:
					ExecCommand( req );
					break;
				case REQ_TYPE_SHISHI_CAI:
					handleShishiCaiSettle(req);
					break;
				case REQ_TYPE_LIANG_HAO:
					handleLianghaoGetUser(req);
					break;
				case REQ_TYPE_DUOBAO:
					handleDuoBaoNotify(req);
					break;
				case REQ_TYPE_BRC_WLD_SETTLE:
					handleBRCWDLSettle(req);
					break;
				case REQ_TYPE_COMMAND_HONGBAO:
					handleCommandHongbaoShangjia(req);
					break;
				case REQ_TYPE_GET_HONGBAO:
					handleGetCommandHongbao(req);
					break;
				case REQ_TYPE_HONGBAO_CONFIRUM:
					handleCommandHongBaoConfirm(req);
					break;
				case REQ_TYPE_HONGBAO_RECORD:
					handleGetCommandHongBaoRecord(req);
					break;
				case REQ_TYPE_FINISH_PAY_YIYUAN_RESLUT:
					handleYiyuanFinishPay(req);
					break;
				case REQ_TYPE_SHARE_REWARD:
					handleGetDailyShareReward(req);
					break;
				default:
					WL(LL_DEV,"cmd = %d not prop\n",req->req_type );
					break;
				
				}
			}

			catch(const char *str)
			{
				g_pFlowLog->logMsg("mysql read err str:%s sql:%s \r\n",str, req->sql);
			}
			SQLMemoryPool::instance()->freeReq( req );
			iter = temp.erase( iter );
			gettimeofday(&tv_end,NULL);
			int user_time = 1000000*(tv_end.tv_sec - tv_start.tv_sec) + (tv_end.tv_usec - tv_start.tv_usec);
			if(user_time > 300000)
			{
				WL(LL_DEV," use_time = %d req->req_type  = %d  size:%d \n",user_time, req->req_type, temp.size());
			}
			
		}
	}
}

DataBaseThread::DataBaseThread()
{

}

DataBaseThread::~DataBaseThread()
{
	m_db.Close();
}

void DataBaseThread::push( SQLReq * req  )
{
	/*SQLReq * req = ( SQLReq *)GlobalObject::getSQLReqPool()->malloc_memory();
	snprintf( req->sql , sizeof(req->sql),"%s",sql ) ;
	req->req_type = req_type ;
	req->client = client ;*/
	m_mutex.lock();
	m_requests.push_back( req );
	m_mutex.unlock();
	m_sem.post_sem();
}

void DataBaseThread::setUserInfo( UserInfo & userInfo , TQuery & query )
{
	userInfo.user_id = query.GetFieldInt("user_id")  ;
	userInfo.set_user_name		(	query.GetFieldValue("user_name"));
	userInfo.level_id =		(	query.GetFieldInt("level_id") ) ;
	userInfo.user_sex =				(	query.GetFieldInt("sex") );
	userInfo.user_face_id =	(	query.GetFieldInt("user_face_id"));
	userInfo.user_score.lost_count =	(	query.GetFieldInt("lost_count"));
	userInfo.user_score.win_count =	(	query.GetFieldInt("win_count"));
	userInfo.set_nick_name		(	query.GetFieldValue("nick_name"));
	userInfo.vip_type =		(	query.GetFieldInt("vip_type"));
	userInfo.set_birthday		(	query.GetFieldValue("birthday"));
	userInfo.userType =		(	query.GetFieldInt("user_type") );
	userInfo.change_card =		(	query.GetFieldInt("change_card") );
	userInfo.four_fold_card =		(	query.GetFieldInt("four_fold_card") );
	userInfo.eight_fold_card =		(	query.GetFieldInt("eight_fold_card") );
	userInfo.ban_than =		(	query.GetFieldInt("ban_than") );
	
	int flowernum = query.GetFieldInt("flower");
	flowernum = flowernum < 0 ? 0 : flowernum;
	userInfo.flower =		(	flowernum );

	int aggsnum = query.GetFieldInt("aggs");
	aggsnum = aggsnum < 0 ? 0 : aggsnum;
	userInfo.aggs =		(	aggsnum );

	int carnum = query.GetFieldInt("car");
	carnum = carnum < 0 ? 0 : carnum;
	userInfo.car =		( carnum );

	int villanum = query.GetFieldInt("villa");
	villanum = villanum < 0 ? 0 : villanum;
	userInfo.villa =		(	villanum );

	int yachtnum = query.GetFieldInt("yacht");
	yachtnum = yachtnum < 0 ? 0 : yachtnum;
	userInfo.yacht =		(	yachtnum );

	userInfo.charm =	(	query.GetFieldInt("charm") );
	
	userInfo.is_give			= query.GetFieldInt("is_give") ;
	userInfo.user_score.diamond		= query.GetFieldInt("diamond");
	userInfo.user_score.gold = ( query.GetFieldLongLong("gold") ) ;
	//printf( "zq setUserInfo userInfo.user_score.gold = %lld\r\n", userInfo.user_score.gold );

	if (userInfo.user_score.gold <= 0)
		userInfo.user_score.gold = 0;

	userInfo.day_play_times = ( query.GetFieldInt("day_play_times") ) ;
	userInfo.conti_login_count	= query.GetFieldInt("conti_login_count");
	userInfo.give_gold_count	= query.GetFieldInt("give_count");
	userInfo.email_count		= query.GetFieldInt("email_count");
	userInfo.today_login		= query.GetFieldInt("today_login");
	userInfo.setVersion( query.GetFieldValue("version"));
	userInfo.broadcast_count	= query.GetFieldInt("broadcast_count");
	userInfo.setContact(query.GetFieldValue("contact"));
	int max_card_model = query.GetFieldInt("max_card_model") ;
	
	userInfo.max_card [ 0 ]=max_card_model%100;
	userInfo.max_card [ 1 ]=(max_card_model/100)%100;
	userInfo.max_card [ 2 ]=(max_card_model/10000)%100;

	userInfo.today_get_help_count		= (BYTE)query.GetFieldInt("today_get_help_count");
	userInfo.tody_get_login_box_count	= (BYTE)query.GetFieldInt("tody_get_login_box_count");
	userInfo.today_get_online_count	= (BYTE)query.GetFieldInt("today_get_online_count");
	userInfo.last_login_time		= query.GetFieldLongLong("last_login_time");

	userInfo.total_win_counts	= query.GetFieldInt("total_win_counts");
	userInfo.total_primary_win_counts	= query.GetFieldInt("total_primary_win_counts");
	userInfo.total_middle_win_counts	= query.GetFieldInt("total_middle_win_counts");
	userInfo.total_high_win_counts	= query.GetFieldInt("total_high_win_counts");
	userInfo.today_game_counts	= query.GetFieldInt("today_game_counts");
	userInfo.today_win_counts	= query.GetFieldInt("today_win_counts");
	userInfo.total_pay_num	= query.GetFieldInt("total_pay_num");
	userInfo.total_use_laba_counts	= query.GetFieldInt("total_use_laba_counts");
	userInfo.set_head_picture( query.GetFieldValue("head_picture") );
	userInfo.tiger_raward_pool = query.GetFieldInt("tiger_raward_pool") ;
	userInfo.paycount = query.GetFieldInt("paycount") ;

	userInfo.set_province(query.GetFieldValue("province"));
	userInfo.isgetfirstgoods = query.GetFieldInt("isgetfirstgoods") ;

	userInfo.taskplaycount = query.GetFieldInt("daily_task_play_count") ;
	userInfo.taskplaywincount = query.GetFieldInt("daily_task_play_win_count") ;

	userInfo.set_char_sign( query.GetFieldValue("sign") );
	userInfo.viplevel = query.GetFieldInt("viplevel") ;
	userInfo.vipovertime = query.GetFieldInt("vipovertime") ;
	userInfo.depositgold = query.GetFieldLongLong("depositgold") ;
	userInfo.set_deposit_pwd( query.GetFieldValue("depositpwd") );
	userInfo.set_phone_number( query.GetFieldValue("phone_number") );
	userInfo.lastdaywingold = query.GetFieldLongLong("lastdaywingold") ;
	userInfo.lastdaypaymoney = query.GetFieldInt("lastdaypaymoney") ;
	userInfo.lotterydrownum = query.GetFieldInt("lotterydrownum") ;
	userInfo.user_score.ticket = query.GetFieldInt("ticket") ;
	userInfo.isadmin = (bool)query.GetFieldInt("isadmin");
	userInfo.texiao = query.GetFieldInt("te_xiao") ;
	userInfo.lianghao = query.GetFieldInt("liang_hao") ;
}


void DataBaseThread::handleLogin( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
		
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	memset( resp->data, 0, sizeof(resp->data) );
	UserInfo * userInfo = ( UserInfo * )resp->data ;
	//printf( "query.IsEof() = %d\r\n", query.IsEof() );
	if ( query.IsEof() )
	{
		resp->result = 0;
	}
	else
	{
		resp->result = 0;
		resp->result = query.GetFieldInt("result") + 1 ;
		//printf( "query.IsEof() = %d\r\n", query.IsEof() );
		if ( resp->result == 1 )
		{
			setUserInfo( *userInfo , query );
		}
	}
	int posindex = sizeof(UserInfo);
	if ( resp->result == 1 )
	{
		//获取用户服务器保存的数据

		//老虎机
		char sqlcmd[128] = {0};
		DBBindPhoneMsg* pReqMsg = (DBBindPhoneMsg*)req->sql;
		snprintf( sqlcmd , sizeof(sqlcmd) , "call SP_Get_User_Temple_Data( %d ) ", userInfo->user_id );
		TQuery tempquery ;
		if ( m_db.ExecuteQuery( sqlcmd, tempquery ) )
		{
			const char* pcards = tempquery.GetFieldValue( "tiger_cards" );
			int tigerchangenum = tempquery.GetFieldInt("tiger_changenum");
			int buygold = tempquery.GetFieldInt("gold");
			int luckcolor = tempquery.GetFieldInt("luckcolor");
			memcpy( resp->data + posindex, pcards, 6 );
			posindex += 6;
			memcpy( resp->data + posindex, &tigerchangenum, 4 );
			posindex += 4;
			memcpy( resp->data + posindex, &buygold, 4 );
			posindex += 4;
			memcpy( resp->data + posindex, &luckcolor, 4 );
			posindex += 4;

		}
	}
	

	
	PUSH_RESP( resp );
}

void DataBaseThread::handleRegister( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		RegisterResult * r = ( RegisterResult *)resp->data ;
		r->result = query.GetFieldInt("result") ;
		r->is_new = query.GetFieldInt("is_new") ;
		const char * tmp = query.GetFieldValue("user_name");
		r->user_name_len		 = strlen( tmp )  ;
		r->user_name_len	= r->user_name_len >= sizeof(r->user_name) ? sizeof(r->user_name) - 1 : r->user_name_len ;
		memcpy( r->user_name , tmp , r->user_name_len ) ;
		r->user_name [ r->user_name_len ] = '\0';
		tmp = query.GetFieldValue("user_pwd");
		r->user_pwd_len		 = strlen( tmp ) ;
		r->user_pwd_len		= r->user_pwd_len >= sizeof(r->user_pwd) ? sizeof(r->user_pwd) - 1 : r->user_pwd_len ;
		memcpy( r->user_pwd , tmp , r->user_pwd_len ) ;
		r->user_pwd [ r->user_pwd_len ] = '\0';
		r->userId = query.GetFieldInt("user_id");
		r->fasted = query.GetFieldInt("fasted");
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleReceiveTaskBonus( SQLReq * req )
{
	printf( "zq DataBaseThread::handleReceiveTaskBonus\r\n" );
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		TaskBonusResult * r = ( TaskBonusResult *)resp->data ;
		r->result = query.GetFieldInt("result") ;
		if ( r->result > 0 )
		{
			r->task_id = query.GetFieldInt("taskid") ;
			r->usergold = query.GetFieldLongLong("gold") ;
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleReceiveHongbaoTaskBonus( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		HongbaoTaskBonusResult * r = ( HongbaoTaskBonusResult *)resp->data ;
		r->result = query.GetFieldInt("result") ;
		if ( r->result > 0 )
		{
			r->task_id = query.GetFieldInt("taskid") ;
			r->gold = query.GetFieldLongLong("gold") ;
			r->diamond = query.GetFieldLongLong("diamond") ;
			r->hongbao = query.GetFieldLongLong("hongbao") ;			
		}
		WL(LL_DEV, "DataBaseThread::handleReceiveHongbaoTaskBonus %s %d %d %d %d\n", req->sql, r->gold, r->diamond, r->hongbao, r->result );
	}
	
	PUSH_RESP( resp );
}

void DataBaseThread::handleRecommendAward( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		RecommendAwardResult * r = ( RecommendAwardResult *)resp->data ;
		r->status = query.GetFieldInt("stat") ;
		r->referee_code = query.GetFieldInt("referee_code") ;
		r->novice_award = query.GetFieldInt("novice_award") ;
		r->award = query.GetFieldInt("recommend_award") ;
		r->newer_ticket = query.GetFieldInt("newer_ticket") ;
		r->ticket_count = query.GetFieldInt("ticket_count") ;
		const char * msg = query.GetFieldValue("msg") ;
		r->msg_len = strlen( msg );
		memcpy( r->msg , msg , r->msg_len );
		r->msg [ r->msg_len ] = '\0' ;
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleExchangeProduct( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		ExchangeProductResult * r = ( ExchangeProductResult *)resp->data ;
		r->result = query.GetFieldInt("result") ;
		r->ticket = query.GetFieldInt("ticket") ;
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleOnlineReward( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		OnlineRewardResult * r = ( OnlineRewardResult *)resp->data ;
		r->result = query.GetFieldInt("result") ;
		r->coin = query.GetFieldInt("coin") ;
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleChargeInfo( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	StreamWriter stream_out((u8_t*)resp->data);
	if ( !query.IsEof() )
	{
		stream_out.add_byte( RESULT_OK );
		stream_out.add_byte(query.GetRowCount());
		while ( !query.IsEof() )
		{
			stream_out.add_byte( query.GetFieldInt("charge_type"));
			stream_out.appand( query.GetFieldValue("charge_type_name"));
			stream_out.add_byte('\0');
			stream_out.appand( query.GetFieldValue("charge_info"));
			stream_out.add_byte('\0');
			query.NextRow();
		}
	}
	resp->len	= stream_out.get_buffer_len();
	PUSH_RESP( resp );
}

void DataBaseThread::handleChargeResult( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		ChargeResult * r = ( ChargeResult *)resp->data ;
		r->charge_status	= query.GetFieldInt("charge_status");//状态
		r->gold			= query.GetFieldInt("gold");		//充值的金币
		r->prop_id			= query.GetFieldInt("prop_id");
		r->prop_count		= query.GetFieldInt("prop_count");
		r->prod_type		= query.GetFieldInt("prod_type");
		r->ticket_count	= query.GetFieldInt("ticket_count");
		r->user_id			= query.GetFieldInt("user_id");
		r->present_prop	= query.GetFieldInt("present_prop");
		r->status	= query.GetFieldInt("status");
		int len =	 0 ;
		const char * charge_id = query.GetFieldValue("charge_id");
		len  = strlen( charge_id );
		memcpy( r->charge_id , charge_id , len );
		r->charge_id [ len ] = '\0';
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleFinishPayResult( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		memset( resp->data, 0, sizeof(resp->data) );
		PayFinishResult * r = ( PayFinishResult *)resp->data ;
		r->result_num	= query.GetFieldInt("result");
		r->userid	= query.GetFieldInt("user_id");
		r->goodsid = query.GetFieldInt("goods_id");
		r->goldnum		= 0;
		r->diamondnum		= 0;
		r->money = 0;
		if ( r->result_num == 1 )
		{
			r->goldnum		= query.GetFieldLongLong("gold");
			r->diamondnum		= query.GetFieldInt("diamond");
			r->viplevel = (BYTE)query.GetFieldInt("viplevel");
			r->vipovertime = (DWORD)query.GetFieldInt("vipovertime");
			r->money = query.GetFieldInt("money");
			r->lotterydrawcount = query.GetFieldInt("addlotterydrawcount");
			r->ticket = query.GetFieldInt("ticket");
			r->vipgrouppoint = query.GetFieldInt("vippoint");
		}
		const char * err_msg = query.GetFieldValue("mailmsg");
		//printf( "err_msg = %s\r\n", err_msg );
		int len  = strlen( err_msg );
		if (len >= MAX_PAY_ERROR_MSG_LEN)
			len = MAX_PAY_ERROR_MSG_LEN-1;
		memcpy( r->errmsg , err_msg , len );
		r->errmsg[len] = '\0';
	}
	PUSH_RESP( resp );
}


void DataBaseThread::handleYiyuanFinishPay(SQLReq * req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		memset( resp->data, 0, sizeof(resp->data) );
		YiyuanPayFinishResult * r = ( YiyuanPayFinishResult *)resp->data ;
		r->result_num	= query.GetFieldInt("result");
		r->userid	= query.GetFieldInt("user_id");

	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleFinishPayOffLine( SQLReq * req  )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
}

void DataBaseThread::handleHttpChargeResult( SQLReq * req )
{
	handleChargeResult( req );
}

void DataBaseThread::handleCreateOrderResult( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		CreateOrderResult * r = ( CreateOrderResult *)resp->data ;
		r->result	= 1;//状态
		int len =	 0 ;
		const char * charge_id = query.GetFieldValue("charge_id");
		len  = strlen( charge_id );
		memcpy( r->charge_id , charge_id , len );
		r->charge_id [ len ] = '\0';
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleUpdateUserInfo( SQLReq * req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		UpdateUserInfoResult * r = ( UpdateUserInfoResult *)resp->data ;
		r->result	= query.GetFieldInt("result");//状态
		if ( r->result == 1 ) //成功
		{
			int len =	 0 ;
			r->sex			= query.GetFieldInt("sex");
			const char * tmp = query.GetFieldValue("username");
			len  = strlen( tmp );
			memcpy( r->username , tmp , len );
			r->username [ len ] = '\0';

			tmp = query.GetFieldValue("pwd");
			len  = strlen( tmp );
			memcpy( r->userpwd , tmp , len );
			r->userpwd [ len ] = '\0';

			tmp = query.GetFieldValue("nickname");
			len  = strlen( tmp );
			memcpy( r->nickname , tmp , len );
			r->nickname [ len ] = '\0';

			tmp = query.GetFieldValue("sign");
			len  = strlen( tmp );
			memcpy( r->charsign , tmp , len );
			r->charsign [ len ] = '\0';

			tmp = query.GetFieldValue("province");
			len  = strlen( tmp );
			memcpy( r->province , tmp , len );
			r->province [ len ] = '\0';

			tmp = query.GetFieldValue("contact");
			len  = strlen( tmp );
			memcpy( r->contact , tmp , len );
			r->contact [ len ] = '\0';

		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleDbUpdateUserInfoEx(SQLReq * req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
				
	}
}

void DataBaseThread::handleRecvSingInAward( SQLReq * req  )
{
	TQuery query ;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd, sizeof(sqlcmd) ,"call SP_User_SignIn(%d)", *(int*)req->sql );
	if ( !m_db.ExecuteQuery( sqlcmd, query ) ){

	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	resp->result	= 0;//状态
	if ( !query.IsEof() )
	{
		int result = query.GetFieldInt("result");//状态 
		printf( "zq handleRecvSingInAward result = %d \r\n", result );
		if (  result == 0 )
		{
			resp->result	= 1;//状态
			int gold = query.GetFieldLongLong("gold");//用户领取后的金币数
			*(int*)resp->data = gold;
			*((int*)resp->data + 1 ) = *((int*)req->sql+1);
		}
	}
	PUSH_RESP( resp );
}

//更新用户财富
void DataBaseThread::ExecCommand( SQLReq * req  )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;//没有返回值result = 0
	//printf( "zq req->client = %x  resp->req_type = %d result = %d\r\n", req->client, resp->req_type, resp->result );
	if ( req->client )
	{
		PUSH_RESP( resp );
	}
	else
	{
		SQLMemoryPool::instance()->freeResp( resp ) ;
	}
}

void DataBaseThread::handleBindAccount( SQLReq * req  )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) )
	{
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		DBBindUserAccount* pUserAccount = (DBBindUserAccount*)resp->data;
		pUserAccount->result = query.GetFieldInt("result");//状态
		//printf( "zq handleBindAccount pUserAccount->result = %d \r\n", pUserAccount->result );
		if ( pUserAccount->result == 0 )
		{
			pUserAccount->userid = query.GetFieldInt("user_id");
			memcpy( pUserAccount->username, query.GetFieldValue( "user_name" ), 32 );
			memcpy( pUserAccount->username, query.GetFieldValue( "user_pwd" ), 32 );
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleBindPhone( SQLReq * req  )
{
	TQuery query ;
	char sqlcmd[256] = {0};
	DBBindPhoneMsg* pReqMsg = (DBBindPhoneMsg*)req->sql;
	snprintf( sqlcmd , sizeof(sqlcmd) , "call SP_Bind_Phone( %u, '%s', '%s' )", pReqMsg->uid, pReqMsg->telephone,pReqMsg->pwd );

	bool result = m_db.ExecuteQuery( sqlcmd, query );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	DBBindPhoneMsg* pRetMsg = (DBBindPhoneMsg*)resp->data;
	memcpy( resp->data, pReqMsg, sizeof(DBBindPhoneMsg) );
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt( "result" );
		if ( pRetMsg->result > 0 )
		{
			pRetMsg->curgold = query.GetFieldLongLong( "gold" );
		}
	}
	PUSH_RESP( resp );
}

//存款
void DataBaseThread::handleDeposit( SQLReq * req  )
{
	TQuery query ;
	bool result = m_db.ExecuteQuery( req->sql , query );

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	DBDepositRetMsg *pRetMsg = (DBDepositRetMsg *)resp->data;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result") ;
		pRetMsg->type = query.GetFieldInt("type") ;
		pRetMsg->usergold = query.GetFieldLongLong("gold") ;
		pRetMsg->depositgold  = query.GetFieldLongLong("depositgold") ;
		pRetMsg->changegold = query.GetFieldLongLong("changegold") ;
	}
	PUSH_RESP( resp );
}



//读排行榜数据，流程6
void DataBaseThread::handleReqSort( SQLReq * req  )
{
	TQuery query ;
	bool result = m_db.ExecuteQuery( "select * from top10 union (select user_id,nick_name,sex,head_picture,total_gold as allgold,0 as type from user_info order by allgold desc limit 10);" , query );

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;

	resp->result = result;

	if (result) {
		//printf( "handleReqSort success \r\n" );
		StreamWriter stream_out(resp->data,sizeof(resp->data));
		short rows = query.GetRowCount();
		//printf("RowCount %d\n",rows);
		stream_out.add_short(rows);
		while ( !query.IsEof() )
		{
			int user_id = query.GetFieldInt("user_id") ;
			string nickname = query.GetFieldValue("nick_name") ;
			unsigned char sex = query.GetFieldInt("sex") ;
			string head_picture = query.GetFieldValue("head_picture") ;
			i64_t gold = query.GetFieldLongLong("allgold") ;
			unsigned char type = query.GetFieldInt("type") ;

			stream_out.add_int(user_id) ;
			stream_out.appand(nickname.c_str(),nickname.length()+1);
			stream_out.add_byte(sex);
			stream_out.appand(head_picture.c_str(),head_picture.length()+1);
			stream_out.add_int64(gold);
			stream_out.add_byte(type);

			//printf("user_id %d,  nickname %s, head_picture %s, gold %lld \n",user_id,nickname.c_str(),head_picture.c_str(),gold);

			query.NextRow();
		}
		query.Finalize();
		resp->len = stream_out.get_buffer_len();
	} else {
		//printf( "handleReqSort failed \r\n" );
	}

	PUSH_RESP( resp );
}

void DataBaseThread::handleUpdateGold( SQLReq * req  )
{
	TQuery query ;
	DBUpdateGold *pUpdateGold = (DBUpdateGold*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd, sizeof(sqlcmd) ,"call Http_UpdateUserWealth( %d, %lld, %d, %d ,%d)", pUpdateGold->userid, pUpdateGold->gold, pUpdateGold->diamond, pUpdateGold->deposit,pUpdateGold->moduletype);
	printf( "zq Http_UpdateUserWealth sqlcmd=%s\r\n", sqlcmd );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	DBUpdateGold *pRetMsg = (DBUpdateGold *)resp->data;

	pRetMsg->result = 0; //默认成功
	pRetMsg->userid = pUpdateGold->userid;
	pRetMsg->gold = pUpdateGold->gold;
	pRetMsg->emailtype = pUpdateGold->emailtype;

	if ( !m_db.ExecuteQuery( sqlcmd, query ) )
	{
		pRetMsg->result = 1; //失败
	}
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->diamond = query.GetFieldInt("diamond");
			pRetMsg->deposit = query.GetFieldInt("deposit");
			//string tips = query.GetFieldValue( "tips" );
			//strncpy( pRetMsg->tips, tips.c_str(), sizeof(pRetMsg->tips) );
		}
	}
	//printf( "zq handleUpdateGold pRetMsg->result=%d req->result=%d\r\n", pRetMsg->result, req->req_type );
	PUSH_RESP( resp );
}

void DataBaseThread::handleUpdateNickName( SQLReq *req )
{
	TQuery query ;
	
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	TUpdate_Nick_Name *pRetMsg = (TUpdate_Nick_Name *)resp->data;

	
	if ( !m_db.ExecuteQuery( req->sql, query ) )
	{
	}
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");
		if ( pRetMsg->result  == 0 )
		{
			pRetMsg->gold =  query.GetFieldLongLong("gold");
			string head_picture = query.GetFieldValue("nickname") ;
			memcpy( pRetMsg->szName , head_picture.c_str(), head_picture.length() );
		}
	}
	PUSH_RESP( resp );
}

//时时彩一轮结束信息
void DataBaseThread::handleLotteryResult( SQLReq *req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;
	//printf( "tt sql=%s \r\n", req->sql );
	if ( req->client )
	{
		PUSH_RESP( resp );
	}
	else
	{
		SQLMemoryPool::instance()->freeResp( resp );
	}
}

void DataBaseThread::handleLotteryMsg( SQLReq *req )
{
	TQuery query ;
	DBLotteryReqMsg *pReqMsg = (DBLotteryReqMsg*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd, sizeof(sqlcmd) ,"call SP_Handle_Lottery_Msg( %lld, %u, %d, %d, %d, %d )", pReqMsg->lotteryid, pReqMsg->uid, pReqMsg->type, pReqMsg->gold,
		pReqMsg->cardtype, pReqMsg->roomid );

	//printf( "tt --handleLotteryMsg sqlcmd=%s, pReqMsg->lotteryid=%lld, pReqMsg->uid=%d, pReqMsg->gold=%u, pRetMsg->type=%d \r\n", sqlcmd, pReqMsg->lotteryid, pReqMsg->uid, pReqMsg->gold, pReqMsg->type );

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	DBLotteryRetMsg *pRetMsg = (DBLotteryRetMsg *)resp->data;
	memset( pRetMsg, 0, sizeof(DBLotteryRetMsg) );
	if ( !m_db.ExecuteQuery( sqlcmd, query ) )
	{
		pRetMsg->result = 1; //失败
	}
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");
		pRetMsg->gold = pReqMsg->gold;
		pRetMsg->cardtype = pReqMsg->cardtype;
		pRetMsg->uid = pReqMsg->uid;
		pRetMsg->type = pReqMsg->type;
	}
	PUSH_RESP( resp );

	//printf( "tt handleLotteryMsg sqlcmd=%s, resp->result=%d, pRetMsg->result=%d, pRetMsg->gold=%lld, pRetMsg->type=%d \r\n", sqlcmd, resp->result, pRetMsg->result, pRetMsg->gold, pRetMsg->type );
}

void DataBaseThread::handleBuyTiger( SQLReq * req  )
{
	//printf( "zq handleBuyTiger ==== \r\n" );
	TQuery query ;
	DBTigerReqMsg *pReqMsg = (DBTigerReqMsg*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Tiger_Handle(%u, %d, %d, '%s', %d, %d, %d )",
		pReqMsg->uid, pReqMsg->reqtype, pReqMsg->buycount, pReqMsg->cards, pReqMsg->cardtype,pReqMsg->buygold, pReqMsg->luckcolor );
	//printf( "zq handleBuyTiger sqlcmd=%s\r\n", sqlcmd );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	DBTigerRetMsg *pRetMsg = (DBTigerRetMsg *)resp->data;
	memset( pRetMsg, 0, sizeof(DBTigerRetMsg) );
	//printf( "zq 222222222222 sqlcmd=%s\r\n", sqlcmd );
	pRetMsg->rsptype = pReqMsg->reqtype;
	pRetMsg->buygold = pReqMsg->buygold;
	pRetMsg->changeindex = pReqMsg->changeindex;
	memcpy( pRetMsg->cards, pReqMsg->cards, 3 );
	//printf( "zq 33333333333 sqlcmd=%s\r\n", sqlcmd );
	if ( !m_db.ExecuteQuery( sqlcmd, query ) )
	{
		pRetMsg->result = 1; //失败
	}
	//printf( "zq 4444444444444 sqlcmd=%s\r\n", sqlcmd );
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");//状态 
		pRetMsg->gold = query.GetFieldLongLong("gold");//用户领取后的金币数
	}
	//printf( "zq 55555555555555 sqlcmd=%s\r\n", sqlcmd );
	//printf( "zq handleBuyTiger pRetMsg->result=%d resp->result=%d\r\n", pRetMsg->result, resp->result );
	PUSH_RESP( resp );

}

void DataBaseThread::handleSendHorn( SQLReq *req )
{
	TQuery query ;
	SEND_HORN* hornmsg = (SEND_HORN*)req->sql;
	char sqlcmd[1024] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Send_Horn(%u,%d,'%s')",
		hornmsg->userid , hornmsg->type, hornmsg->content );
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		DB_SEND_HORN_RESULT* pRetMsg = (DB_SEND_HORN_RESULT*)resp->data;
		pRetMsg->len = hornmsg->len;
		memcpy( pRetMsg->content, hornmsg->content, sizeof(pRetMsg->content) );
		pRetMsg->result = query.GetFieldInt("result");//状态 
		pRetMsg->gold = query.GetFieldLongLong("gold");//用户当前金币
		pRetMsg->usegold = query.GetFieldInt("usegold");//用户使用金币
		pRetMsg->userid = req->id;
	}
	PUSH_RESP( resp );
	
}

void DataBaseThread::handleTransferGold( SQLReq *req )
{
	TQuery query ;
	DBTransferGoldMsg* pReqMsg = (DBTransferGoldMsg*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Transfer_Gold( %u,%lld,%u)", pReqMsg->userid , pReqMsg->gold, pReqMsg->touserid );
	//printf( "handleTransferGold : %s \r\n", sqlcmd );
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		DBTransferGoldMsg* pRetMsg = (DBTransferGoldMsg*)resp->data;
		memcpy( pRetMsg, pReqMsg, sizeof(DBTransferGoldMsg) );
		pRetMsg->result = query.GetFieldInt("result");//状态 
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->gold = query.GetFieldLongLong("gold");//状态 
			pRetMsg->togold = query.GetFieldLongLong("togold");//状态 
			pRetMsg->rate = query.GetFieldInt("rate");
			pRetMsg->touseroldgold =  query.GetFieldLongLong("to_old_gold");
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleTransferGoldRecord( SQLReq *req )
{
	TQuery query ;
	DWORD userid = *(DWORD*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Get_Transfer_Record( %u)", userid );
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;	//可能没有数据  这里设置为1
	memset( resp->data, 0, sizeof(resp->data) );
	DBTransferGoldRectList *recordlist = (DBTransferGoldRectList *)resp->data;
	while ( !query.IsEof() )
	{
		recordlist->data[recordlist->len].touserid = query.GetFieldInt("touserid");
		recordlist->data[recordlist->len].fromuserid = query.GetFieldInt("fromuserid");
		recordlist->data[recordlist->len].transfergold = query.GetFieldInt("transfergold");
		recordlist->data[recordlist->len].time = query.GetFieldInt("operatortime");
		//string nickname = query.GetFieldValue("nickname") ;
		//memcpy( recordlist->data[recordlist->len].nicknmae, nickname.c_str(), sizeof(recordlist->data[recordlist->len].nicknmae) );
		recordlist->len++;
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleGetChatMessage( SQLReq *req )
{
	TQuery query ;
	char sqlcmd[128] = {0};
	USER_REQ_CHAT_DATA* reqmsg = (USER_REQ_CHAT_DATA*)req->sql;
	snprintf( sqlcmd, sizeof(sqlcmd) , "call SP_Chat_Get_Chat_Message( %u, %u )",  reqmsg->userid, reqmsg->fromuserid );
	//printf( "sqlcmd = %s\r\n", sqlcmd );
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;//可能没有消息
	USER_CHAT_RECORD_ARRAY *pRetMsg = (USER_CHAT_RECORD_ARRAY*)resp->data;
	pRetMsg->fromuserid = reqmsg->fromuserid;
	pRetMsg->count = 0;
	while ( !query.IsEof() )
	{
		pRetMsg->list[pRetMsg->count].time = query.GetFieldInt("sendtime");
		string content = query.GetFieldValue("content") ;
		strncpy( pRetMsg->list[pRetMsg->count].content, content.c_str(),sizeof(pRetMsg->list[pRetMsg->count].content) - 1 );
		//printf( "pRetMsg->list[pRetMsg->count].content = %s\r\n", pRetMsg->list[pRetMsg->count].content );
		pRetMsg->count++;
		query.NextRow();
	}
	PUSH_RESP( resp );
}


void DataBaseThread::handleLotteryDraw( SQLReq *req )
{
	TQuery query ;
	DBLotteryDrawMsg* pReqMsg = (DBLotteryDrawMsg*)req->sql;
	char sqlcmd[128] = {0};
	//1免费 2金币
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_LotteryDraw_Handle( %u, %d, %d, %d)", pReqMsg->useid, pReqMsg->type, pReqMsg->goodsid, pReqMsg->times  );
	m_db.ExecuteQuery( sqlcmd , query );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	DBLotteryDrawRetMsg * pRetMsg = (DBLotteryDrawRetMsg *)resp->data;
	pRetMsg->type = pReqMsg->type;
	pRetMsg->times = pReqMsg->times;
	pRetMsg->goodsid = pReqMsg->goodsid;

	while ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->curgold = query.GetFieldLongLong("gold");
			//printf( "pRetMsg->curgold = %lld\r\n", pRetMsg->curgold );
			pRetMsg->lotterynum = query.GetFieldInt("lotterycount");
			pRetMsg->changevalue = query.GetFieldInt("changevalue");
			pRetMsg->goodstype = query.GetFieldInt("goodstype");
		}
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleGetUserWealth( SQLReq *req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;
	DB_GET_USER_WEALTH *pRetMsg = (DB_GET_USER_WEALTH*)resp->data;
	if ( !query.IsEof() )
	{
		pRetMsg->gold = query.GetFieldLongLong("gold");
		pRetMsg->diamond = query.GetFieldInt("diamond");
		pRetMsg->ticket = query.GetFieldInt("ticket");
		strncpy( pRetMsg->message, query.GetFieldValue("message"), sizeof(pRetMsg->message) - 1 );
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleBuyOrSellGoods( SQLReq *req )
{
	TQuery query ;
	DB_BUY_SELLGOODS_DATA* pReqMsg = (DB_BUY_SELLGOODS_DATA*)req->sql;
	char sqlcmd[128] = {0};
	//1卖 2买
	//snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_LotteryDraw_Handle( %u, %d, %d, %d)", pReqMsg->useid, pReqMsg->type, pReqMsg->goodsid, pReqMsg->times  );
	snprintf( sqlcmd , sizeof(sqlcmd) , "SELECT gold, diamond, ticket FROM user_info WHERE user_id = %u;",  pReqMsg->userid );
	m_db.ExecuteQuery( sqlcmd , query );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp, 0, sizeof(SQLResp) );
	resp->clone( req, !query.IsEof() ) ;
	DB_BUY_SELLGOODS_DATA_RET* pRetMsg = (DB_BUY_SELLGOODS_DATA_RET*)resp->data;
	pRetMsg->type = pReqMsg->type;
	pRetMsg->userid = pReqMsg->userid;
	memcpy( pRetMsg->emailcontent, pReqMsg->emailcontent, sizeof(pRetMsg->emailcontent) );
	while ( !query.IsEof() )
	{
		pRetMsg->gold = query.GetFieldLongLong("gold");
		pRetMsg->diamond = query.GetFieldInt("diamond");
		pRetMsg->ticket = query.GetFieldInt("ticket");
		query.NextRow();
	}
	PUSH_RESP( resp );
}


void DataBaseThread::handleSellGift( SQLReq *req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	DB_SELL_GIFT_RET *pRetMsg = (DB_SELL_GIFT_RET*)resp->data;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldLongLong("result");
		pRetMsg->gold = query.GetFieldLongLong("gold");
		pRetMsg->sellgold = query.GetFieldInt("sellgold");
		pRetMsg->giftid = query.GetFieldInt("gifttype");
		pRetMsg->giftcount = query.GetFieldInt("giftcount");
		pRetMsg->charmnum = query.GetFieldInt("charm");
		pRetMsg->giftnum = query.GetFieldInt("giftnum");
		//printf( "zq  db pRetMsg->charmnum = %d \r\n" , pRetMsg->charmnum );
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleGiveGift( SQLReq *req )
{
	//printf( "handleGiveGift=\r\n" );
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	DB_GIVE_GIFT_RET *pRetMsg = (DB_GIVE_GIFT_RET*)resp->data;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldLongLong("result");
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->gold = query.GetFieldLongLong("gold");
			pRetMsg->giftid = query.GetFieldInt("giftid");
			pRetMsg->userid = query.GetFieldInt("userid");
			pRetMsg->giftcount = 1;//
			pRetMsg->giveuid =  query.GetFieldInt("giveuid");
			pRetMsg->changegold = query.GetFieldInt("changegold");
			pRetMsg->charmnum = query.GetFieldInt("charm");
		}
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleClearLastDayVar( SQLReq *req )
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	DB_CLEAR_LASTDAY_VAR *pRetMsg = (DB_CLEAR_LASTDAY_VAR*)resp->data;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldLongLong("result");
		pRetMsg->logintime = query.GetFieldInt("last_login_time");
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->continueday = query.GetFieldInt("conti_login_count");
			pRetMsg->onlineboxcount = query.GetFieldInt("today_get_online_count");
			pRetMsg->helpcount = query.GetFieldInt("today_get_help_count");;//
			pRetMsg->wincount =  query.GetFieldInt("today_win_counts");
			pRetMsg->playcount = query.GetFieldInt("today_game_counts");
			pRetMsg->drawcount = query.GetFieldInt("lotterydrawcount");
		}
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleFriendAddByGift( SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	if (!query.IsEof())
	{		
		int result = query.GetFieldInt("result");
		stream_out.add_byte( result );
		//printf( "zq handleFriendAddByGift result = %d\r\n", result );
		if ( result == 0 )
		{
			stream_out.add_uint( query.GetFieldInt("src_userid") );
			stream_out.add_uint( query.GetFieldInt("des_userid") );
			stream_out.add_int( query.GetFieldInt("giftid"));

			stream_out.add_byte( (BYTE)query.GetFieldInt("sex") );
			stream_out.add_int64( query.GetFieldLongLong("gold") );

			const char * tmp = NULL;
			tmp	= query.GetFieldValue("head_picture");	
			int tmp_len = strlen(tmp);
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);

			tmp	= query.GetFieldValue("nick_name");	
			tmp_len = strlen(tmp);
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);

			tmp	= query.GetFieldValue("sign");	
			tmp_len = strlen(tmp);
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);

			stream_out.add_int64( query.GetFieldLongLong("src_gold") );
			stream_out.add_int( query.GetFieldInt("giftnum") );
			//printf( "giftnum = %d\r\n", query.GetFieldInt("giftnum") );
			stream_out.add_int( query.GetFieldInt("charm") );
		}
	}
	resp->len	= stream_out.get_buffer_len();
	if ( req->client )
	{
		PUSH_RESP( resp ) ;
	}
	else
	{
		SQLMemoryPool::instance()->freeResp(resp);
	}

}

//百人场结算
void DataBaseThread::handleBRCSettle(SQLReq* req)
{
	SERVER_BRC_CHIP_NOTIFY* pReqMsg = (SERVER_BRC_CHIP_NOTIFY*)req->sql;

	
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) , "CALL SP_BRC_Settle(%d, %lld, %d, %lld, %d) ",  pReqMsg->uid, pReqMsg->varmoney, pReqMsg->rategold, pReqMsg->gameid ,6);

	TQuery query ;
	m_db.ExecuteQuery( sqlcmd , query );

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp, 0, sizeof(SQLResp) );
	DB_PLAYR_SETTLT_RET *pRetMsg = (DB_PLAYR_SETTLT_RET*)resp->data;
	
	pRetMsg->uid = pReqMsg->uid;
	pRetMsg->changegold = pReqMsg->varmoney;
	resp->clone( req, !query.IsEof() ) ;
	
	while ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");

		pRetMsg->gold = query.GetFieldLongLong("gold");

		//g_pFlowLog->logMsg(" DataBaseThread::handleBRCSettle  result:%d  gold:%lld nUserID:%d", pRetMsg->result, pRetMsg->gold, pRetMsg->uid);
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleBRCWDLSettle(SQLReq* req)
{
	BRC_BANK_WLD_SETTLE_NOTIFY* pReqMsg = (BRC_BANK_WLD_SETTLE_NOTIFY*)req->sql;

	
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) , "CALL SP_BRC_WLD_Settle(%d, %lld, %d, %lld, %d, %lld,%lld,%lld,%d) ",  pReqMsg->uid, pReqMsg->varmoney, pReqMsg->rategold, \
		pReqMsg->gameid ,6, pReqMsg->winBet, pReqMsg->loseBet, pReqMsg->drawsBet, pReqMsg->openType);
	//g_pFlowLog->logMsg("handleBRCWDLSettle  sql:%s", sqlcmd);
	TQuery query ;
	m_db.ExecuteQuery( sqlcmd , query );

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp, 0, sizeof(SQLResp) );
	DB_PLAYR_SETTLT_RET *pRetMsg = (DB_PLAYR_SETTLT_RET*)resp->data;
	
	pRetMsg->uid = pReqMsg->uid;
	pRetMsg->changegold = pReqMsg->varmoney;
	resp->clone( req, !query.IsEof() ) ;
	
	while ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");

		pRetMsg->gold = query.GetFieldLongLong("gold");

		//g_pFlowLog->logMsg(" DataBaseThread::handleBRCSettle  result:%d  gold:%lld nUserID:%d", pRetMsg->result, pRetMsg->gold, pRetMsg->uid);
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleBRCGetLottery(SQLReq *req)
{
	TQuery query ;
	m_db.ExecuteQuery(req->sql, query);

	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset(resp, 0, sizeof(SQLResp) );
	DB_LOTTERY_RET *pRetMsg = (DB_LOTTERY_RET*)resp->data;

	resp->clone( req, !query.IsEof() ) ;
	while ( !query.IsEof() )
	{
		pRetMsg->gold = query.GetFieldLongLong("lotteryvalue");
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleEnterRoomCheck(SQLReq* req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	DB_ENTER_ROOM_CHECK *pMsg = (DB_ENTER_ROOM_CHECK*)(resp->data);
	
	while ( !query.IsEof() )
	{
		pMsg->gold = query.GetFieldLongLong("gold");
		query.NextRow();
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleUpdateGiftNum(SQLReq *req)
{
	TQuery query ;
	DBUpdateGift *pDbGift = (DBUpdateGift*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd, sizeof(sqlcmd) ,"call Http_UpdateUserGift( %d, %d, %d, %d )", pDbGift->userid, pDbGift->giftid, pDbGift->giftnum, pDbGift->ticket );

	printf( "zq Http_UpdateUserGift sqlcmd=%s\r\n", sqlcmd );
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	DBUpdateGift *pRetMsg = (DBUpdateGift *)resp->data;
	memcpy(pRetMsg->content, pDbGift->content, sizeof(pDbGift->content));

	pRetMsg->result = 0; //默认成功
	pRetMsg->userid = pDbGift->userid;
	if ( !m_db.ExecuteQuery( sqlcmd, query ) )
	{
		pRetMsg->result = 1; //失败
	}
	resp->clone( req , !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		pRetMsg->result = query.GetFieldInt("result");
		if ( pRetMsg->result == 0 )
		{	
			pRetMsg->giftid= query.GetFieldInt("gift");
			pRetMsg->userid = query.GetFieldInt("userid");
			pRetMsg->giftnum = query.GetFieldInt("giftnum");
			pRetMsg->ticket = query.GetFieldInt("ticket");
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread:: handleShishiCaiSettle(SQLReq *req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;

	tShishiCaiBetRet *pRet = (tShishiCaiBetRet*)resp->data;
	
	if( !query.IsEof() )
	{
		pRet->result = query.GetFieldInt("result");
		if(pRet->result == 0)
		{
			pRet->gold = query.GetFieldLongLong("gold");
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleLianghaoGetUser(SQLReq *req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;

	DB_GET_BID_USER *pRet = (DB_GET_BID_USER*)resp->data;

	int idx = 0;
	while ( !query.IsEof() )		//暂时设计成最多存1024个
	{
		int nUserID = query.GetFieldInt("user_id");
		idx++;
		memcpy((void *)(pRet->szContent +idx-1), &nUserID, sizeof(int));
		query.NextRow();
		if(idx >= 1024)
		{
			break;
		}
	}
	pRet->count = idx;
	PUSH_RESP( resp );
}

void DataBaseThread::handleDuoBaoNotify(SQLReq *req)
{
	TQuery query ;
	if ( !m_db.ExecuteQuery( req->sql , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;

	DB_GET_DUOBAO_NOTIFY *pRet = (DB_GET_DUOBAO_NOTIFY*)resp->data;
	
	if ( !query.IsEof() )
	{
		pRet->nResult = query.GetFieldInt("result");
		if(pRet->nResult == 0)
		{
			memcpy((void *)pRet->szContent, query.GetFieldValue("content"), sizeof(pRet->szContent));
		}
	}
	PUSH_RESP( resp );
}

void DataBaseThread::handleCommandHongbaoShangjia(SQLReq *req)
{
	TQuery query ;
	DB_COMMAND_HONGBAO_MSG *pReqMsg = (DB_COMMAND_HONGBAO_MSG*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Command_Hongbao( %u,%lld)", pReqMsg->uid , pReqMsg->gold);
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		DB_COMMAND_HONGBAO_MSG* pRetMsg = (DB_COMMAND_HONGBAO_MSG*)resp->data;
		memcpy( pRetMsg, pReqMsg, sizeof(DB_COMMAND_HONGBAO_MSG) );
		pRetMsg->result = query.GetFieldInt("result");//状态 
		if ( pRetMsg->result == 0 )
		{
			pRetMsg->gold = query.GetFieldLongLong("gold");
			pRetMsg->togold = query.GetFieldLongLong("togold");//转出金额
			pRetMsg->command_code = query.GetFieldInt("command_code");

			//printf("handleCommandHongbaoShangjia uid:%d gold:%lld togold:%lld  command:%d \n", pReqMsg->uid, pRetMsg->gold, pRetMsg->togold, pRetMsg->command_code);
		}
	}

	
	
	PUSH_RESP( resp );	
}

void DataBaseThread::handleGetCommandHongbao(SQLReq *req)
{
	
	TQuery query ;
	DB_COMMAND_HONGBAO_MSG *pReqMsg = (DB_COMMAND_HONGBAO_MSG*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Get_Command_Hongbao( %u,%lld)", pReqMsg->uid , pReqMsg->command_code);
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() );
	
	if ( !query.IsEof() )
	{
		DB_COMMAND_HONGBAO_MSG* pRetMsg = (DB_COMMAND_HONGBAO_MSG*)resp->data;
		memcpy( pRetMsg, pReqMsg, sizeof(DB_COMMAND_HONGBAO_MSG) );
	
		pRetMsg->result = query.GetFieldInt("result");
		if(0 == pRetMsg->result)
		{
			pRetMsg->gold = query.GetFieldLongLong("gold");
			pRetMsg->orther_uid = query.GetFieldInt("from_uid");
			printf("DataBaseThread::handleGetCommandHongbao hongbao gold:%lld from_uid:%d \n", pRetMsg->gold, pRetMsg->orther_uid);
		}
	}

	
	PUSH_RESP( resp );	

	
}


void DataBaseThread::handleCommandHongBaoConfirm(SQLReq * req)
{
	TQuery query ;
	DB_COMMAND_HONGBAO_CONFIIM *pReqMsg = (DB_COMMAND_HONGBAO_CONFIIM*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Confirm_Command_Hongbao( %u,%d, %d)", pReqMsg->uid, pReqMsg->commond_code, pReqMsg->type);
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	if ( !query.IsEof() )
	{
		DB_COMMAND_HONGBAO_CONFIIM* pRetMsg = (DB_COMMAND_HONGBAO_CONFIIM*)resp->data;
		memcpy( pRetMsg, pReqMsg, sizeof(DB_COMMAND_HONGBAO_CONFIIM) );
		pRetMsg->result = query.GetFieldInt("result");//状态 
		if (0 == pRetMsg->result)
		{
			pRetMsg->gold = query.GetFieldLongLong("gold");
			pRetMsg->to_uid = query.GetFieldInt("to_uid");
			printf("DataBaseThread::handleCommandHongBaoConfirm hongbao gold:%lld to_uid:%d \n", pRetMsg->gold, pRetMsg->to_uid);
		}
	}
	
	PUSH_RESP( resp );
}

void DataBaseThread::handleGetCommandHongBaoRecord(SQLReq * req)
{

	TQuery query ;
	DWORD userid = *(DWORD*)req->sql;
	char sqlcmd[128] = {0};
	snprintf( sqlcmd , sizeof(sqlcmd) ,"call SP_Get_Hongbao_Record( %u)", userid );
	if ( !m_db.ExecuteQuery( sqlcmd , query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	resp->result = 1;	//可能没有数据  这里设置为1
	memset( resp->data, 0, sizeof(resp->data) );
	DB_HONGBAO_RectList *recordlist = (DB_HONGBAO_RectList *)resp->data;
	while ( !query.IsEof() )
	{
		recordlist->data[recordlist->len].userid = query.GetFieldInt("user_id");
		recordlist->data[recordlist->len].orther_userid = query.GetFieldInt("other_id");
		recordlist->data[recordlist->len].transfergold = query.GetFieldInt("money");
		recordlist->data[recordlist->len].command_code = query.GetFieldInt("command_id");
		recordlist->data[recordlist->len].time = query.GetFieldInt("operate_time");
		recordlist->data[recordlist->len].rb_type = query.GetFieldInt("type");
		recordlist->data[recordlist->len].rb_status = query.GetFieldInt("rb_status");
		recordlist->len++;
		query.NextRow();
	}
	PUSH_RESP( resp );

}


void DataBaseThread::handleGetDailyShareReward(SQLReq * req)
{
	
	TQuery query ;
	
	if ( !m_db.ExecuteQuery( req->sql, query ) ){
	}
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req, !query.IsEof() ) ;
	TDB_DAILY_SHARE_REWARD *pData = (TDB_DAILY_SHARE_REWARD *)resp->data;
	while ( !query.IsEof() )
	{
	
		pData->type = query.GetFieldInt("type");
		pData->result = query.GetFieldInt("result");
		pData->money = query.GetFieldInt("gold");
		pData->scene_id = query.GetFieldInt("scene");
		if( pData->result == 0 )
		{
			pData->result = 1;
			
		}
		else
		{
			pData->result = -1;
		}
		query.NextRow();
	}
	PUSH_RESP( resp );
}
////////////////////////////////////////////////////////////////////////////////////
DataBasePacketDataThread::DataBasePacketDataThread()
{

}

DataBasePacketDataThread::~DataBasePacketDataThread()
{
	m_db.Close();
}

void DataBasePacketDataThread::push( SQLReq * req  )
{
	m_mutex.lock();
	m_requests.push_back( req );
	m_mutex.unlock();
	m_sem.post_sem();
}


bool DataBasePacketDataThread::connect( const char * ip , int port , const char * dbname , const char * username , const char * userpwd , int conns)
{	
	return m_db.Open( ip , dbname , username , userpwd ,port, gettid());
}

void DataBasePacketDataThread::update()
{
	
	SQLReq * req = SQLMemoryPool::instance()->mallocReq();
	snprintf( req->sql , sizeof(req->sql) ,"select 3");
	req->req_type	= REQ_TYPE_DB_HEAT ;
	DataBasePacketDataThread::instance()->push( req );

	PipeEventHandler::instance()->on_printf();

}
void DataBasePacketDataThread::run( void * object )
{
#if __THREAD_MYSQL_CONNECT__
	DbConfig &m_db_acct			= Config::instance()->m_account_db;
	if ( !connect( m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name , m_db_acct.db_username,m_db_acct.db_userpwd) )
	{
		printf("connect acct db faild ip =%s port=%d db=%s name=%s pwd=%s cn=%d\n",
			m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name ,
			m_db_acct.db_username,m_db_acct.db_userpwd ,Config::instance()->m_db_connect_count);
		return ;
	}
#endif
	while ( 1 )
	{
		int nRet = 0;	
		/*nRet = m_sem.wait_sem(5);
		//WL(LL_FATAL, "DataBasePacketDataThread  wait_sem	nRet:%d  \r\n", nRet);
		if(1 == nRet)
		{
			//WL(LL_FATAL, "DataBasePacketDataThread  wait_sem	timeout  \r\n");
			continue;
		}
		else if(2 == nRet)
		{
			WL(LL_FATAL,"DataBasePacketDataThread  wait_sem  err \r\n");
			continue;
		}*/

		 m_sem.wait_sem();
		
		SQLRequestList temp ;
		m_mutex.lock();
		if ( m_requests.size() > 0 ){
			SQLRequestList::iterator iter = m_requests.begin();
			for ( ; iter != m_requests.end() ; iter++){
				temp.push_back( *iter );
			}

			//printf("temp 11 size:%d \n", temp.size());
			m_requests.clear();
		}
		m_mutex.unlock();
		SQLRequestList::iterator iter = temp.begin();
		for ( ; iter != temp.end() ;)
		{
			struct  timeval    tv_start, tv_end;  gettimeofday(&tv_start,NULL);
			SQLReq * req = (*iter);
			try
			{
				switch ( req->req_type )
				{
				case REQ_TYPE_EMAIL_LIST:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleEmailList( req , query );
					}
					break;
				case REQ_TYPE_TASK_LIST:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleTaskList( req , query );
					}
					break;
				case REQ_TYPE_HONGBAO_TASK_LIST:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleHongbaoTaskList( req , query );
					}
					break;

				case REQ_TYPE_HONGBAO_NUM:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleHongbaoNum( req , query );
					}
					break;
				case REQ_TYPE_FREE_HONGBAO:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleFreeHongbao( req , query );
					}
					break;
				case REQ_TYPE_OPEN_HONGBAO:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleOpenHongbao( req , query );
					}
					break;
				case REQ_TYPE_HONGBAO_HISTORY:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleHongbaoHistory( req , query );
					}
					break;
					
				case REQ_TYPE_UPDATE_TASK:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_ACTIVE_LIST:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						//handleActiveList( req , query );
					}
					break;
				case REQ_TYPE_CREATE_ORDER:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						//handleCreateOrder( req , query );
					}
					break;
				case REQ_TYPE_ORDER_CONFIRM:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						//handleOrderConfirm( req , query );
					}
				case REQ_TYPE_EXCHAGE_RECORD:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleExchangeRecord( req , query );
						break;
					}
					break;
				case REQ_TYPE_UPDATE_HEAD_PICTURE:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;

				case REQ_TYPE_FRIEND_GET_LIST:
					{
						handleFriendGetList( req );
					}
					break;
				case REQ_TYPE_FRIEND_ADD:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_FRIEND_ADD_MSG:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_FRIEND_DELETE:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_GET_USER_DETAIL:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleGetUserDetail( req , query );
					}
					break;
				case REQ_TYPE_EMAIL_DELETE:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_ENEMY_DELETE:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_ENEMY_UPDATE_OR_ADD:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_ENEMY_GET_LIST:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
						handleEnemyGetList( req , query );
					}
					break;
				case REQ_TYPE_ADD_EMAIL:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_OFFLINE_LOTTERY_OVER:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_DB_HEAT:
					{
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){
							//DBErrorLog( req->sql );
						}
					}
					break;
				case REQ_TYPE_LOGIN:
					{
						struct  timeval    tv_start;
						gettimeofday(&tv_start,NULL);

						int time = tv_start.tv_sec *1000000  + tv_start.tv_usec;
						
						WL(LL_DEV, "db handleLogin  const time:%d sql[%s]\n", time - req->time_stamp, req->sql);
						TQuery query ;
						if ( !m_db.ExecuteQuery( req->sql , query ) ){

						}
						handleLogin(req, query);
					}
					break;
				default:
					break;
				}
			}
			catch(const char *str)
			{
				g_pFlowLog->logMsg("DataBasePacketDataThread  mysql read err:%s sql:%s\r\n",str, req->sql);
			}

			SQLMemoryPool::instance()->freeReq( req );
			iter = temp.erase( iter );

			gettimeofday(&tv_end,NULL);
			int user_time = 1000000*(tv_end.tv_sec - tv_start.tv_sec) + (tv_end.tv_usec - tv_start.tv_usec);
			if(user_time > 300000)
			{
				WL(LL_DEV," use_time = %d req->req_type  = %d   size:%d  \n",user_time, req->req_type, temp.size());
				
			}
		}
	}
}
void DataBasePacketDataThread::handleEmailList(SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	stream_out.add_byte( RESULT_OK );
	int record_count = query.GetRowCount();

	DWORD userId = 0;
	DWORD email_id = 0;


	//char desBuff[1024];
	//int desbufflen = sizeof(desBuff);

	//邮件数
	stream_out.add_word( record_count );
	bool		need_update = false ;
	while ( !query.IsEof() )
	{
		userId = query.GetFieldInt("user_id");
		DWORD emp_email_id = query.GetFieldInt("email_id");
		stream_out.add_uint( emp_email_id );
		BYTE read_flag	= query.GetFieldInt("is_read") ;
		if ( read_flag == 0 ) need_update  = true ;
		stream_out.add_byte( read_flag ) ;						//是否已读，0，未读，1，已读
		stream_out.add_byte( query.GetFieldInt("email_type") ) ;//类别

		const char * tmp = NULL;
		tmp	= query.GetFieldValue("opera_date");				//操作时间
		int tmp_len = strlen(tmp);
		stream_out.add_short( tmp_len );
		stream_out.appand( tmp, tmp_len );
		//printf( "*************email tmp = %s\r\n", tmp );
		tmp = query.GetFieldValue("content");					//邮件内容
		
		//memset(desBuff, 0, desbufflen);
		//CsvDataMgr::instance()->gb2312toutf8((char *)tmp, strlen(tmp), desBuff, desbufflen-1);
		//desBuff[desbufflen-1] = '\0';

		tmp_len = strlen(tmp);
		stream_out.add_short( tmp_len );
		stream_out.appand( tmp, tmp_len );

		if (email_id == 0)
			email_id = emp_email_id;
		if (emp_email_id < email_id)
			email_id = emp_email_id;

		query.NextRow();
	}
	if ( need_update )
	{
		SQLReq * q = SQLMemoryPool::instance()->mallocReq();
		snprintf( q->sql , sizeof(q->sql),"update user_email set is_read = 1 where user_id=%u",userId );
		DataBaseCommitThread::instance()->push( q ) ;
	}

	if (record_count >= 20) {
		SQLReq * q = SQLMemoryPool::instance()->mallocReq();
		snprintf( q->sql , sizeof(q->sql),"DELETE FROM user_email WHERE user_id=%u and email_id < %u; ", userId, email_id);
		DataBaseCommitThread::instance()->push( q ) ;
	}

	resp->len	= stream_out.get_buffer_len();
	PUSH_RESP( resp ) ;
}

void DataBasePacketDataThread::handleTaskList( SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	
	//任务数
	stream_out.add_word( (WORD)record_count );
	while ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("task_id") ) ;		//任务ID
		stream_out.add_byte( (BYTE)query.GetFieldInt("task_status") ) ;	//任务状态，0未完成, 1未领奖励，2完成
		stream_out.add_int( query.GetFieldInt("finishtime") ) ;		//任务ID
		query.NextRow();
	}
	resp->len	= stream_out.get_buffer_len();
	PUSH_RESP( resp ) ;
}

void DataBasePacketDataThread::handleHongbaoNum(SQLReq * req , TQuery & query )
{
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	
	if ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("hongbao") ) ;
	}
	else
	{
		stream_out.add_int(0) ;		
	}
	resp->len	= stream_out.get_buffer_len();	
	PUSH_RESP( resp );
}

void DataBasePacketDataThread::handleFreeHongbao(SQLReq * req , TQuery & query )
{
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
//	resp->clone( req , !query.IsEof() ) ;
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);	
	if ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("result") ) ;		
	}
	else
	{
		stream_out.add_int( 1 ) ;				
	}
	resp->len	= stream_out.get_buffer_len();	
	PUSH_RESP( resp );
}
void DataBasePacketDataThread::handleOpenHongbao(SQLReq * req , TQuery & query )
{
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	if ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("result") ) ;
		stream_out.add_int( query.GetFieldInt("type") ) ;
		stream_out.add_int( query.GetFieldInt("value") ) ;				
	}
	else
	{
		stream_out.add_int( 1 ) ;
		stream_out.add_int( 0 ) ;
		stream_out.add_int( 0 ) ;						
	}
	resp->len	= stream_out.get_buffer_len();		
	PUSH_RESP( resp );
}
void DataBasePacketDataThread::handleHongbaoHistory(SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	
	//任务数
	stream_out.add_word( (WORD)record_count );
	while ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("reward_type") ) ;
		stream_out.add_int( query.GetFieldInt("reward_value") ) ;		
		stream_out.add_byte( (BYTE)query.GetFieldInt("already_send") ) ;
		stream_out.add_int( query.GetFieldInt("oper_time") ) ;
		query.NextRow();
	}
	resp->len	= stream_out.get_buffer_len();
	PUSH_RESP( resp ) ;
}

void DataBasePacketDataThread::handleHongbaoTaskList( SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	
	//任务数
	stream_out.add_word( (WORD)record_count );
	while ( !query.IsEof() )
	{
		stream_out.add_int( query.GetFieldInt("task_id") ) ;		//任务ID
		stream_out.add_byte( (BYTE)query.GetFieldInt("task_status") ) ;	//任务状态，0未完成, 1未领奖励，2完成
		stream_out.add_int( query.GetFieldInt("finishtime") ) ;		//任务ID
		stream_out.add_int( query.GetFieldInt("task_value") ) ;	
		query.NextRow();
	}
	resp->len	= stream_out.get_buffer_len();
	PUSH_RESP( resp ) ;
}

void DataBasePacketDataThread::handleExchangeRecord( SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	stream_out.add_byte( RESULT_OK );
	int record_count = query.GetRowCount() ;
	stream_out.add_word( record_count );
	while ( !query.IsEof() )
	{
		stream_out.add_byte( query.GetFieldInt("receive") ) ;			//是否领取,0:未领取，1：领取
		stream_out.add_uint( query.GetFieldInt("total_ticket") ) ;		//用多少兑换券兑换
		const char * tmp = NULL ;
		tmp	= query.GetFieldValue("exch_name");		
		stream_out.appand( tmp );										//兑换的商品名称,以’\0’结尾
		stream_out.add_byte( '\0');
		tmp	= query.GetFieldValue("opera_date");						//兑换日期,以’\0’结尾
		stream_out.appand( tmp );
		stream_out.add_byte( '\0');
		tmp = query.GetFieldValue("receive_date");						//领取日期,以’\0’结尾，未领取时为空
		stream_out.appand( tmp );
		stream_out.add_byte( '\0');
		query.NextRow();
	}
	resp->len	= stream_out.get_buffer_len();
	//assert(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) );
	if(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN))
	{
		PUSH_RESP( resp ) ;
	}
}

void DataBasePacketDataThread::handleFriendGetList(SQLReq * req)
{
	DWORD totalfriendnum = 20;
	DWORD userid = *(int*)req->sql;
	int pos = 0;
	while ( true )
	{
		char sqlcmd[128] = {0};
		TQuery query ;
		snprintf( sqlcmd, sizeof(sqlcmd) ,"call sp_friend_get_list(%u, %d, %d)", userid, pos, totalfriendnum );
		if ( !m_db.ExecuteQuery( sqlcmd , query ) )
		{
			break;
		}
		SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
		memset( resp->data, 0, sizeof(resp->data) );
		resp->client	= req->client ;
		resp->req_type	= req->req_type ;
		resp->result	= !query.IsEof() ;
		StreamWriter stream_out((u8_t*)resp->data);
		int record_count = query.GetRowCount() ;
		stream_out.add_word( record_count );
		while (!query.IsEof())
		{		
			stream_out.add_uint( query.GetFieldInt("friend_id") ) ;	
			stream_out.add_int64( query.GetFieldLongLong("add_time") ) ;	
			const char * tmp = NULL;
			tmp	= query.GetFieldValue("nickname");	
			int tmp_len = strlen(tmp);
			if (strlen(tmp) <= 0) {
				tmp	= query.GetFieldValue("model");	
				stream_out.add_word(strlen(tmp));
				stream_out.appand(tmp);
			}
			else {
				stream_out.add_word(tmp_len);
				stream_out.appand(tmp);
			}

			tmp	= query.GetFieldValue("head_picture");	
			tmp_len = strlen(tmp);
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);

			stream_out.add_int64( query.GetFieldLongLong("gold") );
			stream_out.add_byte( query.GetFieldInt("sex") );

			tmp	= query.GetFieldValue("sign");	
			tmp_len = strlen(tmp);
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);
			stream_out.add_int( query.GetFieldLongLong("msgcount") );
			query.NextRow();
		}
		resp->len	= stream_out.get_buffer_len();
		//assert(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) );
		if(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) )
		{
			PUSH_RESP( resp ) ;
		}
		//分批读取	读取完后退出	
		pos += totalfriendnum;
		if ( record_count < totalfriendnum )
		{
			break;
		}
	}
}

void DataBasePacketDataThread::handleEnemyGetList(SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	stream_out.add_word( record_count );
	while (!query.IsEof())
	{		
		stream_out.add_uint( query.GetFieldInt("enemy_id") ) ;	
		stream_out.add_int64( query.GetFieldLongLong("add_time") ) ;	
		const char * tmp = NULL;
		tmp	= query.GetFieldValue("nick_name");	
		int tmp_len = strlen(tmp);
		if (strlen(tmp) <= 1) {
			tmp	= query.GetFieldValue("user_name");	
			stream_out.add_word(strlen(tmp));
			stream_out.appand(tmp);
		}
		else {
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);
		}

		tmp	= query.GetFieldValue("head_picture");	
		tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);

		stream_out.add_uint( query.GetFieldInt("lost_gold") );
		stream_out.add_byte( query.GetFieldInt("sex") );

		tmp	= query.GetFieldValue("sign");	
		tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);

		query.NextRow();
	}
	resp->len	= stream_out.get_buffer_len();
	//assert(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) );
	if(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) )
	{
		PUSH_RESP( resp ) ;
	}
}

void DataBasePacketDataThread::handleGetUserDetail( SQLReq * req , TQuery & query )
{
	SQLResp * resp	= ( SQLResp *)SQLMemoryPool::instance()->mallocResp();
	memset( resp->data, 0, sizeof(resp->data) );
	resp->client	= req->client ;
	resp->req_type	= req->req_type ;
	resp->result	= !query.IsEof() ;
	StreamWriter stream_out((u8_t*)resp->data);
	int record_count = query.GetRowCount() ;
	if (!query.IsEof())
	{		
		stream_out.add_byte( RESULT_OK );

		stream_out.add_uint( query.GetFieldInt("user_id") );
		stream_out.add_byte( (BYTE)query.GetFieldInt("sex") );
		stream_out.add_byte( (BYTE)query.GetFieldInt("vip_type") );
		stream_out.add_uint( query.GetFieldInt("face_id"));
		stream_out.add_word( (WORD)query.GetFieldInt("level_id") );
		stream_out.add_int64( query.GetFieldLongLong("gold") );
		stream_out.add_uint( query.GetFieldInt("diamond") );
		stream_out.add_uint( query.GetFieldInt("ticket") );

		stream_out.add_uint( query.GetFieldInt("flower") );
		stream_out.add_uint( query.GetFieldInt("aggs") );
		stream_out.add_uint( query.GetFieldInt("car") );
		stream_out.add_uint( query.GetFieldInt("villa") );
		stream_out.add_uint( query.GetFieldInt("yacht") );
		stream_out.add_uint( query.GetFieldInt("charm") );

		stream_out.add_int( query.GetFieldInt("win_count") );
		stream_out.add_int( query.GetFieldInt("lost_count") );

		stream_out.add_int(query.GetFieldInt("max_card_model"));

		const char * tmp = NULL;
		tmp	= query.GetFieldValue("head_picture");	
		int tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);

		tmp	= query.GetFieldValue("nick_name");	
		tmp_len = strlen(tmp);
		if (strlen(tmp) <= 1) {
			tmp	= query.GetFieldValue("user_name");	
			stream_out.add_word(strlen(tmp));
			stream_out.appand(tmp);
		}
		else {
			stream_out.add_word(tmp_len);
			stream_out.appand(tmp);
		}

		tmp	= query.GetFieldValue("province");	
		tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);

		tmp	= query.GetFieldValue("contact");	
		tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);


		tmp	= query.GetFieldValue("sign");	
		tmp_len = strlen(tmp);
		stream_out.add_word(tmp_len);
		stream_out.appand(tmp);
		stream_out.add_int(query.GetFieldInt("te_xiao"));
		//printf( "zq tmp = %s tmp_len = %d\r\n", tmp, tmp_len );

		query.NextRow();
	}
	else {
		stream_out.add_byte( RESULT_FAILD );
	}

	resp->len	= stream_out.get_buffer_len();
	//assert(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN) );
	if(resp->len< (sizeof(resp->data) - PACKET_HEAD_LEN))
	{
		PUSH_RESP( resp ) ;
	}
}


void DataBasePacketDataThread::handleLogin(SQLReq * req,TQuery & query)
{

	struct  timeval    tv;  gettimeofday(&tv,NULL);
	
	SQLResp * resp = SQLMemoryPool::instance()->mallocResp() ;
	memset( resp->data, 0, sizeof(resp->data) );
	resp->clone( req , !query.IsEof() ) ;
	memset( resp->data, 0, sizeof(resp->data) );
	UserInfo * userInfo = ( UserInfo * )resp->data ;
	//printf( "query.IsEof() = %d\r\n", query.IsEof() );
	if ( query.IsEof() )
	{
		resp->result = 0;
	}
	else
	{
		resp->result = 0;
		resp->result = query.GetFieldInt("result") + 1 ;
		//printf( "query.IsEof() = %d\r\n", query.IsEof() );
		if ( resp->result == 1 )
		{
			setUserInfo( *userInfo , query );
		}
	}
	
	int posindex = sizeof(UserInfo);
	if ( resp->result == 1 )
	{
		//获取用户服务器保存的数据

		//老虎机
		char sqlcmd[128] = {0};
		DBBindPhoneMsg* pReqMsg = (DBBindPhoneMsg*)req->sql;
		snprintf( sqlcmd , sizeof(sqlcmd) , "call SP_Get_User_Temple_Data( %d ) ", userInfo->user_id );
		TQuery tempquery ;
		if ( m_db.ExecuteQuery( sqlcmd, tempquery ) )
		{
			const char* pcards = tempquery.GetFieldValue( "tiger_cards" );
			int tigerchangenum = tempquery.GetFieldInt("tiger_changenum");
			int buygold = tempquery.GetFieldInt("gold");
			int luckcolor = tempquery.GetFieldInt("luckcolor");
			memcpy( resp->data + posindex, pcards, 6 );
			posindex += 6;
			memcpy( resp->data + posindex, &tigerchangenum, 4 );
			posindex += 4;
			memcpy( resp->data + posindex, &buygold, 4 );
			posindex += 4;
			memcpy( resp->data + posindex, &luckcolor, 4 );
			posindex += 4;

		}
	}

	struct  timeval    tv_start;  gettimeofday(&tv_start,NULL);
	int time_stamp = tv_start.tv_sec *1000000  + tv_start.tv_usec;
	resp->time_stamp =  time_stamp;
	PUSH_RESP( resp );
}


void DataBasePacketDataThread:: setUserInfo( UserInfo & userInfo , TQuery & query )
{
	userInfo.user_id = query.GetFieldInt("user_id")  ;
	userInfo.set_user_name		(	query.GetFieldValue("user_name"));
	userInfo.level_id =		(	query.GetFieldInt("level_id") ) ;
	userInfo.user_sex =				(	query.GetFieldInt("sex") );
	userInfo.user_face_id =	(	query.GetFieldInt("user_face_id"));
	userInfo.user_score.lost_count =	(	query.GetFieldInt("lost_count"));
	userInfo.user_score.win_count =	(	query.GetFieldInt("win_count"));
	userInfo.set_nick_name		(	query.GetFieldValue("nick_name"));
	userInfo.vip_type =		(	query.GetFieldInt("vip_type"));
	userInfo.set_birthday		(	query.GetFieldValue("birthday"));
	userInfo.userType =		(	query.GetFieldInt("user_type") );
	userInfo.change_card =		(	query.GetFieldInt("change_card") );
	userInfo.four_fold_card =		(	query.GetFieldInt("four_fold_card") );
	userInfo.eight_fold_card =		(	query.GetFieldInt("eight_fold_card") );
	userInfo.ban_than =		(	query.GetFieldInt("ban_than") );
	
	int flowernum = query.GetFieldInt("flower");
	flowernum = flowernum < 0 ? 0 : flowernum;
	userInfo.flower =		(	flowernum );

	int aggsnum = query.GetFieldInt("aggs");
	aggsnum = aggsnum < 0 ? 0 : aggsnum;
	userInfo.aggs =		(	aggsnum );

	int carnum = query.GetFieldInt("car");
	carnum = carnum < 0 ? 0 : carnum;
	userInfo.car =		( carnum );

	int villanum = query.GetFieldInt("villa");
	villanum = villanum < 0 ? 0 : villanum;
	userInfo.villa =		(	villanum );

	int yachtnum = query.GetFieldInt("yacht");
	yachtnum = yachtnum < 0 ? 0 : yachtnum;
	userInfo.yacht =		(	yachtnum );

	userInfo.charm =	(	query.GetFieldInt("charm") );
	
	userInfo.is_give			= query.GetFieldInt("is_give") ;
	userInfo.user_score.diamond		= query.GetFieldInt("diamond");
	userInfo.user_score.gold = ( query.GetFieldLongLong("gold") ) ;
	//printf( "zq setUserInfo userInfo.user_score.gold = %lld\r\n", userInfo.user_score.gold );

	if (userInfo.user_score.gold <= 0)
		userInfo.user_score.gold = 0;

	userInfo.day_play_times = ( query.GetFieldInt("day_play_times") ) ;
	userInfo.conti_login_count	= query.GetFieldInt("conti_login_count");
	userInfo.give_gold_count	= query.GetFieldInt("give_count");
	userInfo.email_count		= query.GetFieldInt("email_count");
	userInfo.today_login		= query.GetFieldInt("today_login");
	userInfo.setVersion( query.GetFieldValue("version"));
	userInfo.broadcast_count	= query.GetFieldInt("broadcast_count");
	userInfo.setContact(query.GetFieldValue("contact"));
	int max_card_model = query.GetFieldInt("max_card_model") ;
	
	userInfo.max_card [ 0 ]=max_card_model%100;
	userInfo.max_card [ 1 ]=(max_card_model/100)%100;
	userInfo.max_card [ 2 ]=(max_card_model/10000)%100;

	userInfo.today_get_help_count		= (BYTE)query.GetFieldInt("today_get_help_count");
	userInfo.tody_get_login_box_count	= (BYTE)query.GetFieldInt("tody_get_login_box_count");
	userInfo.today_get_online_count	= (BYTE)query.GetFieldInt("today_get_online_count");
	userInfo.last_login_time		= query.GetFieldLongLong("last_login_time");

	userInfo.total_win_counts	= query.GetFieldInt("total_win_counts");
	userInfo.total_primary_win_counts	= query.GetFieldInt("total_primary_win_counts");
	userInfo.total_middle_win_counts	= query.GetFieldInt("total_middle_win_counts");
	userInfo.total_high_win_counts	= query.GetFieldInt("total_high_win_counts");
	userInfo.today_game_counts	= query.GetFieldInt("today_game_counts");
	userInfo.today_win_counts	= query.GetFieldInt("today_win_counts");
	userInfo.total_pay_num	= query.GetFieldInt("total_pay_num");
	userInfo.total_use_laba_counts	= query.GetFieldInt("total_use_laba_counts");
	userInfo.set_head_picture( query.GetFieldValue("head_picture") );
	userInfo.tiger_raward_pool = query.GetFieldInt("tiger_raward_pool") ;
	userInfo.paycount = query.GetFieldInt("paycount") ;

	userInfo.set_province(query.GetFieldValue("province"));
	userInfo.isgetfirstgoods = query.GetFieldInt("isgetfirstgoods") ;

	userInfo.taskplaycount = query.GetFieldInt("daily_task_play_count") ;
	userInfo.taskplaywincount = query.GetFieldInt("daily_task_play_win_count") ;

	userInfo.set_char_sign( query.GetFieldValue("sign") );
	userInfo.viplevel = query.GetFieldInt("viplevel") ;
	userInfo.vipovertime = query.GetFieldInt("vipovertime") ;
	userInfo.depositgold = query.GetFieldLongLong("depositgold") ;
	userInfo.set_deposit_pwd( query.GetFieldValue("depositpwd") );
	userInfo.set_phone_number( query.GetFieldValue("phone_number") );
	userInfo.lastdaywingold = query.GetFieldLongLong("lastdaywingold") ;
	userInfo.lastdaypaymoney = query.GetFieldInt("lastdaypaymoney") ;
	userInfo.lotterydrownum = query.GetFieldInt("lotterydrownum") ;
	userInfo.user_score.ticket = query.GetFieldInt("ticket") ;
	userInfo.isadmin = (bool)query.GetFieldInt("isadmin");
	userInfo.texiao = query.GetFieldInt("te_xiao") ;
	userInfo.lianghao = query.GetFieldInt("liang_hao") ;
}
void DataBaseCommitThread::push( SQLReq * req  )
{
// 	SQLReq * req = ( SQLReq *)GlobalObject::getSQLReqPool()->malloc_memory();
// 	snprintf( req->sql , sizeof(req->sql),"%s",sql ) ;
	req->req_type = REQ_TYPE_DDL ;
	req->client = NULL ;
	m_mutex.lock();
	m_requests.push_back( req );
	m_mutex.unlock();
}


void DataBaseCommitThread::update()
{
	SQLReq * req = SQLMemoryPool::instance()->mallocReq();
	//snprintf( req->sql , sizeof(req->sql) ,"select 2");
	snprintf(req->sql,sizeof(req->sql), "update user_info set gold=gold+0 where user_id = 0 limit 1");	///模拟一条定时任务去查询数据库/
	DataBaseCommitThread::instance()->push( req );
}

void DataBaseCommitThread::run( void * object )
{
#if __THREAD_MYSQL_CONNECT__
	DbConfig &m_db_acct			= Config::instance()->m_account_db;
	if ( !connect( m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name , m_db_acct.db_username,m_db_acct.db_userpwd) )
	{
		printf("connect acct db faild ip =%s port=%d db=%s name=%s pwd=%s cn=%d\n",
			m_db_acct.db_ip ,m_db_acct.db_port , m_db_acct.db_name ,
			m_db_acct.db_username,m_db_acct.db_userpwd ,Config::instance()->m_db_connect_count);
		return ;
	}
#endif
	while ( 1 )
	{
#ifdef WIN32
		Sleep(1000);
#else
		sleep(1);
#endif

		SQLRequestList temp ;
		m_mutex.lock();
		if ( m_requests.size() > 0 )
		{
			temp = m_requests ;
			m_requests.clear();
		}
		m_mutex.unlock();
		m_db.BegintTransaction();
		SQLRequestList::iterator iter = temp.begin();
		for ( ; iter != temp.end() ;)
		{
			SQLReq * req = (*iter);
			if ( !m_db.ExecuteNonQuery( req->sql  ) ){
				//DBErrorLog( req->sql );
			}
			SQLMemoryPool::instance()->freeReq( req );
			iter = temp.erase( iter );
		}
		m_db.Commit();
	}
}

DataBaseCommitThread::DataBaseCommitThread()
{

}

DataBaseCommitThread::~DataBaseCommitThread()
{
	m_db.Close();
}

bool DataBaseReadThreadPool::InitThread( int conns )
{
	for ( int i = 0 ; i < conns ; i++)
	{
		DataBaseThread * th = new DataBaseThread ;
		m_threads.push_back( th );
	}
	return true ;
}

void DataBaseReadThreadPool::pushQueue( SQLReq * req )
{
	int threadindex = req->id%m_threads.size();
	m_threads [ threadindex ]->push( req );
	//WL(LL_INFO, "sql.id:%d  sql.type:%d   sql.client:0x%x \n", req->id,req->req_type, req->client);
}

void DataBaseReadThreadPool::run()
{
	for ( int i = 0 ; i < m_threads.size() ; i++)
	{
		DataBaseThread * th = m_threads [ i ] ;
		th->start_run() ;
	}
}


void DataBaseReadThreadPool::update()
{
	for ( int i = 0 ; i < m_threads.size() ; i++)
	{
		DataBaseThread * th = m_threads [ i ] ;
		th->update(i) ;
	}
}
